import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/user.dart';
import 'dependencies.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

/// 认证状态
abstract class AuthState {}

class AuthInitial extends AuthState {}

class AuthLoading extends AuthState {}

class AuthSuccess extends AuthState {
  final User user;
  AuthSuccess(this.user);
}

class AuthError extends AuthState {
  final String message;
  AuthError(this.message);
}

/// 认证状态通知器
class AuthStateNotifier extends Notifier<AuthState> {
  late final Ref _ref;

  @override
  AuthState build() {
    _ref = ref;
    return AuthInitial();
  }

  /// 登录
  Future<void> login(String username, String password,
      {bool? isOnlineOverride}) async {
    state = AuthLoading();

    try {
      // 检查网络连接状态
      bool isOnline;
      if (isOnlineOverride != null) {
        // 使用传入的网络状态（手动模式）
        isOnline = isOnlineOverride;
      } else {
        // 自动检测网络状态
        final connectivityResult = await Connectivity().checkConnectivity();
        isOnline =
            connectivityResult.contains(ConnectivityResult.none) == false;
      }

      print(
          '登录请求: username=$username, isOnline=$isOnline, isOnlineOverride=$isOnlineOverride');

      final authUseCases = _ref.read(authUseCasesProvider);

      if (!isOnline) {
        // 离线模式：尝试使用本地存储的认证信息登录
        try {
          final storedUserInfo = await authUseCases.getStoredUserInfo();
          print('离线登录：本地存储的用户信息: $storedUserInfo');
          print('离线登录：输入的用户名: $username');

          if (storedUserInfo != null) {
            print('本地存储的用户名: ${storedUserInfo.username}');
            if (storedUserInfo.username == username) {
              // 用户名匹配，创建用户对象
              final user = User(
                id: storedUserInfo.id,
                username: storedUserInfo.username,
                email: storedUserInfo.email,
                role: storedUserInfo.role,
                orgName: storedUserInfo.orgName,
                avatarUrl: storedUserInfo.avatarUrl,
              );
              print('离线登录成功：用户 $username');
              state = AuthSuccess(user);
              return;
            } else {
              print('用户名不匹配: 本地=${storedUserInfo.username}, 输入=$username');
              state = AuthError('离线模式下无匹配的本地用户信息');
              return;
            }
          } else {
            print('离线登录失败：离线模式下无本地用户信息');
            state = AuthError('离线模式下无本地用户信息');
            return;
          }
        } catch (e) {
          print('离线登录异常：${e.toString()}');
          state = AuthError('离线登录失败：${e.toString()}');
          return;
        }
      }

      // 在线模式：执行正常的登录流程
      print('执行在线登录流程');
      final result = await authUseCases.login(
        username: username,
        password: password,
      );

      print(
          '在线登录结果: isSuccess=${result.isSuccess}, data=${result.data}, errorMessage=${result.errorMessage}');
      if (result.isSuccess && result.data != null) {
        // 将LoginResponse中的UserInfo转换为User实体
        final userInfo = result.data!.user;
        final user = User(
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          role: userInfo.role,
          orgName: userInfo.orgName,
          avatarUrl: userInfo.avatarUrl,
        );

        // 确保用户信息已保存到本地存储（以防saveLoginData未被调用）
        try {
          final authUseCases = _ref.read(authUseCasesProvider);
          await authUseCases.saveUserInfo(userInfo);
          print('用户信息已保存到本地存储');
        } catch (e) {
          print('保存用户信息到本地存储时出错: $e');
        }
        state = AuthSuccess(user);
      } else {
        state = AuthError(result.errorMessage ?? '登录失败');
      }
    } catch (e) {
      // 提供更详细的错误信息
      String errorMessage = '登录失败';
      if (e.toString().contains('SocketException') ||
          e.toString().contains('无网络连接')) {
        errorMessage = '网络连接失败，请检查网络设置或使用本地存储的认证信息';
      } else if (e.toString().contains('401')) {
        errorMessage = '用户名或密码错误';
      } else {
        errorMessage = '登录失败：${e.toString()}';
      }
      print('登录异常: $errorMessage');
      state = AuthError(errorMessage);
    }
  }

  /// 登出
  Future<void> logout({bool clearLocalData = false}) async {
    try {
      final authUseCases = _ref.read(authUseCasesProvider);
      await authUseCases.logout(clearLocalData: clearLocalData);
      state = AuthInitial();
    } catch (e) {
      state = AuthError('登出失败：${e.toString()}');
    }
  }

  /// 绕过登录直接进入主页面（用于测试）
  void bypassLogin() {
    // 创建一个模拟的用户信息
    final user = User(
      id: 1,
      username: 'admin',
      email: 'admin@flowplan.com',
      role: 'ADMIN',
      orgName: 'FlowPlan团队',
      avatarUrl: null,
    );
    state = AuthSuccess(user);
  }

  /// 同步用户信息
  Future<void> syncUserInfo() async {
    try {
      final authUseCases = _ref.read(authUseCasesProvider);
      final result = await authUseCases.getCurrentUser(forceUpdate: true);

      if (result.isSuccess && result.data != null) {
        final userInfo = result.data!;
        final user = User(
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          role: userInfo.role,
          orgName: userInfo.orgName,
          avatarUrl: userInfo.avatarUrl,
        );

        // 更新当前状态
        if (state is AuthSuccess) {
          state = AuthSuccess(user);
        }
      }
    } catch (e) {
      // 静默处理同步错误，不影响当前状态
      print('同步用户信息失败: $e');
    }
  }

  /// 检查登录状态
  Future<void> checkAuthStatus({bool? isOnlineOverride}) async {
    try {
      final authUseCases = _ref.read(authUseCasesProvider);

      // 首先检查网络连接状态
      bool isOnline;
      if (isOnlineOverride != null) {
        // 使用传入的网络状态（手动模式）
        isOnline = isOnlineOverride;
      } else {
        // 自动检测网络状态
        final connectivityResult = await Connectivity().checkConnectivity();
        isOnline =
            connectivityResult.contains(ConnectivityResult.none) == false;
      }

      if (isOnline) {
        // 在线模式：从服务器获取用户信息
        final result = await authUseCases.getCurrentUser();

        if (result.isSuccess && result.data != null) {
          final userInfo = result.data!;
          final user = User(
            id: userInfo.id,
            username: userInfo.username,
            email: userInfo.email,
            role: userInfo.role,
            orgName: userInfo.orgName,
            avatarUrl: userInfo.avatarUrl,
          );
          state = AuthSuccess(user);
        } else {
          state = AuthInitial();
        }
      } else {
        // 离线模式：尝试从本地获取用户信息
        try {
          final storedUserInfo = await authUseCases.getStoredUserInfo();

          if (storedUserInfo != null) {
            final user = User(
              id: storedUserInfo.id,
              username: storedUserInfo.username,
              email: storedUserInfo.email,
              role: storedUserInfo.role,
              orgName: storedUserInfo.orgName,
              avatarUrl: storedUserInfo.avatarUrl,
            );
            state = AuthSuccess(user);
          } else {
            state = AuthInitial();
          }
        } catch (innerE) {
          // 如果本地也没有用户信息，则认为未登录
          state = AuthInitial();
        }
      }
    } catch (e) {
      // 改进网络错误处理
      if (e.toString().contains('无网络连接') ||
          e.toString().contains('SocketException') ||
          e.toString().contains('远程计算机拒绝网络连接')) {
        // 网络连接失败时，尝试从本地获取用户信息
        try {
          final authUseCases = _ref.read(authUseCasesProvider);
          final storedUserInfo = await authUseCases.getStoredUserInfo();

          if (storedUserInfo != null) {
            final user = User(
              id: storedUserInfo.id,
              username: storedUserInfo.username,
              email: storedUserInfo.email,
              role: storedUserInfo.role,
              orgName: storedUserInfo.orgName,
              avatarUrl: storedUserInfo.avatarUrl,
            );
            state = AuthSuccess(user);
            return;
          }
        } catch (innerE) {
          // 静默处理内部错误
        }
      }
      state = AuthInitial();
    }
  }
}

/// 认证状态Provider
final authStateProvider =
    NotifierProvider<AuthStateNotifier, AuthState>(AuthStateNotifier.new);

/// 当前用户Provider
final currentUserProvider = Provider<User?>((ref) {
  final authState = ref.watch(authStateProvider);
  return authState is AuthSuccess ? authState.user : null;
});

/// 是否已登录Provider
final isLoggedInProvider = Provider<bool>((ref) {
  final authState = ref.watch(authStateProvider);
  return authState is AuthSuccess;
});
